import { useCallback, useEffect, useRef, useState } from 'react';
import { BrowserCompatibility, checkBrowserCompatibility, getCompatibilitySuggestions, setupIOSSpeechSynthesis } from './isIOS';


// 在原有的接口基础上添加兼容性信息
interface SpeechService extends BrowserCompatibility {
  // 原有的TTS相关方法...
  isSpeaking: boolean;
  
  // 原有的录音相关方法...
  isRecording: boolean;
  startRecording: () => Promise<void>;
  stopRecording: () => Promise<Blob>;
  
  // 原有的匹配相关方法...
  isMatching: boolean;
  
  // 新增的兼容性信息
  compatibility: BrowserCompatibility;
  suggestions: string[];
}
/**
 * 语音服务Hook - 提供TTS、录音和语音匹配功能
 * 兼容Android、HarmonyOS和iOS浏览器
 */
export const useSpeechService = (): SpeechService => {
    const [compatibility, setCompatibility] = useState<BrowserCompatibility>(() => 
    checkBrowserCompatibility()
  );
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [isMatching, setIsMatching] = useState(false);
  
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioChunksRef = useRef<Blob[]>([]);
  // 在组件挂载时执行兼容性检查
  useEffect(() => {
    const currentCompatibility = checkBrowserCompatibility();
    setCompatibility(currentCompatibility);
    setSuggestions(getCompatibilitySuggestions(currentCompatibility));
    
    // iOS特殊处理
    const cleanup = setupIOSSpeechSynthesis();
    
    return cleanup;
  }, []);

  /**
   * 开始录音
   */
  const startRecording = useCallback(async (): Promise<void> => {
    return new Promise(async (resolve, reject) => {
      // 检查兼容性
      if (!compatibility.recording) {
        reject(new Error('您的浏览器不支持录音功能'));
        return;
      }
      
      if (!compatibility.mimeType) {
        reject(new Error('无法找到支持的音频格式'));
        return;
      }
      
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ 
          audio: {
            echoCancellation: true,
            noiseSuppression: true,
            autoGainControl: true
          } 
        });
        
        // 使用检测到的兼容MIME类型
        const options = { 
          mimeType: compatibility.mimeType,
          audioBitsPerSecond: 128000
        };
        
        const mediaRecorder = new MediaRecorder(stream, options);
         mediaRecorderRef.current = mediaRecorder;
        audioChunksRef.current = [];
        
        // 收集音频数据
        mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            audioChunksRef.current.push(event.data);
          }
        };
        
        mediaRecorder.onstop = () => {
          // 停止所有音频轨道
          stream.getTracks().forEach(track => track.stop());
        };
        
        mediaRecorder.onerror = (event) => {
          reject(new Error(`录音错误: ${event.error}`));
        };
        
        // 开始录音
        mediaRecorder.start(100); // 每100ms收集一次数据
        setIsRecording(true);
        resolve();
      } catch (error) {
        reject(new Error(`无法访问麦克风: ${error}`));
      }
    });
  }, [compatibility.recording, compatibility.mimeType]);

  /**
   * 停止录音并返回音频Blob
   */
  const stopRecording = useCallback(async (): Promise<Blob> => {
    return new Promise((resolve, reject) => {
      if (!mediaRecorderRef.current || !isRecording) {
        reject(new Error('没有正在进行的录音'));
        return;
      }
      
      const mediaRecorder = mediaRecorderRef.current;
      
      mediaRecorder.onstop = async () => {
        setIsRecording(false);
        const audioBlob = new Blob(audioChunksRef.current, { 
          type: 'audio/webm;codecs=opus' 
        });
        resolve(audioBlob);
      };
      
      mediaRecorder.stop();
      mediaRecorderRef.current = null;
    });
  }, [isRecording]);


  return {
    isSpeaking,
    isRecording,
    startRecording,
    stopRecording,
    isMatching,
     compatibility,
    suggestions,
    // 展开compatibility的所有属性以便直接访问
    ...compatibility
  };
};